package com.yy.wga.wechat.service.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedissonConfigImpl;
import com.google.common.collect.Maps;
import com.yy.wga.common.core.enmus.EResponseCode;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.common.util.common.EnvUtils;
import com.yy.wga.merchant.feign.api.MerchantInfoFeign;
import com.yy.wga.merchant.feign.response.MerchantMpConfigInfoResp;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author wannianqing
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
@Profile("pro")
public class WxMaConfiguration {
    @Value("${wx.officialAccount.appId:}")
    private String officialAccountAppId;
    @Value("${wx.officialAccount.secret:}")
    private String officialAccountSecret;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private MerchantInfoFeign merchantInfoFeign;

    private static final Map<String, WxMaService> maServiceHashMap = Maps.newHashMap();

    private static final WxMpService officialAccountWxService = new WxMpServiceImpl();

    public static WxMpService getOfficialAccountService() {
        return officialAccountWxService;
    }

    public static WxMaService getMaService() {
        WxMaService wxMaService = maServiceHashMap.get(EnvUtils.get("merchant.appKey"));
        if (wxMaService == null) {
            throw new IllegalArgumentException("未找到微信配置，请核实！");
        }
        return wxMaService;
    }

    public static WxMaService getChannelMaService() {
        WxMaService wxMaService = maServiceHashMap.get("channel-" + EnvUtils.get("merchant.appKey"));
        if (wxMaService == null) {
            throw new IllegalArgumentException("未找到微信配置，请核实！");
        }
        return wxMaService;
    }

    public static String getToken() {
        WxMaService maService = WxMaConfiguration.getMaService();
        try {
            return maService.getAccessToken();
        } catch (WxErrorException e) {
            log.error("获取token异常", e);
            throw new BusinessException(EResponseCode.SYSTEM_BUSY_ERROR);
        }
    }

    /**
     * 获取视频号token
     *
     * @return
     */
    public static String getChannelToken() {
        WxMaService maService = WxMaConfiguration.getChannelMaService();
        try {
            return maService.getAccessToken();
        } catch (WxErrorException e) {
            log.error("获取token异常", e);
            throw new BusinessException(EResponseCode.SYSTEM_BUSY_ERROR);
        }
    }

    @PostConstruct
    public void init() {
        List<MerchantMpConfigInfoResp> configList = merchantInfoFeign.list().getData();
        if (CollectionUtils.isEmpty(configList)) {
            throw new WxRuntimeException("找不到小程序相关配置");
        }
        for (MerchantMpConfigInfoResp mpConfig : configList) {
            WxMaRedissonConfigImpl config = new WxMaRedissonConfigImpl(redissonClient, mpConfig.getAppId());
            config.setAppid(mpConfig.getAppId());
            config.setSecret(mpConfig.getSecret());
            WxMaService service = new WxMaServiceImpl();
            service.setWxMaConfig(config);
            maServiceHashMap.put(mpConfig.getAppKey(), service);
            WxMaRedissonConfigImpl channelConfig = new WxMaRedissonConfigImpl(redissonClient, mpConfig.getAppId());
            channelConfig.setAppid(mpConfig.getChannelAppId());
            channelConfig.setSecret(mpConfig.getChannelSecret());
            WxMaService channelService = new WxMaServiceImpl();
            channelService.setWxMaConfig(channelConfig);
            maServiceHashMap.put("channel-" + mpConfig.getAppKey(), channelService);
        }
        // 微信公众号配置
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(officialAccountAppId);
        config.setSecret(officialAccountSecret);
        officialAccountWxService.setWxMpConfigStorage(config);
    }
}
